package com.yujistu.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.imagepipeline.request.Postprocessor;

/**
 * Created by S3YOGA on 2015/11/4.
 */
public class YuJiSimpleDraweView extends SimpleDraweeView {
    LoadSuccessListener listener;
    String url;

    public interface LoadSuccessListener {
        void onLoadSuccess(String url, Bitmap bitmap);
    }

    public YuJiSimpleDraweView(Context context, GenericDraweeHierarchy hierarchy) {
        super(context, hierarchy);
    }

    public YuJiSimpleDraweView(Context context) {
        super(context);
    }

    public YuJiSimpleDraweView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public YuJiSimpleDraweView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setUrl(String url, LoadSuccessListener listener) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        this.listener = listener;
        Uri uri = Uri.parse(url);
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .setPostprocessor(postprocessor).build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setTapToRetryEnabled(true)
                .build();
        setController(controller);
    }

    private Postprocessor postprocessor = new BasePostprocessor() {
        @Override
        public void process(Bitmap bitmap) {
            super.process(bitmap);
            if (listener != null) {
                listener.onLoadSuccess(url, bitmap);
            }
        }
    };

}
